package com.warmlight.voicepacket.adapter;

import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.widget.RelativeLayout;

import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.warmlight.voicepacket.R;
import com.warmlight.voicepacket.data.RecommendData;
import com.warmlight.voicepacket.data.RecommendFeed;
import com.warmlight.voicepacket.http.Callback;
import com.warmlight.voicepacket.http.HttpClient;
import com.warmlight.voicepacket.http.HttpConfig;
import com.warmlight.voicepacket.widget.CoverLoading;
import com.warmlight.voicepacket.widget.FooterListView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

import okhttp3.Call;

import static com.warmlight.voicepacket.http.HttpConfig.DISCOVER_FEED;
import static com.warmlight.voicepacket.http.HttpConfig.SERVER;

public class CommunityPagerAdapter extends PagerAdapter {

    private List<RecommendData.DataBean.CategoryBean> mList;
    private Context mContext;

    public CommunityPagerAdapter(Context context, List<RecommendData.DataBean.CategoryBean> list) {
        mList = list;
        mContext = context;
    }

    @Override
    public int getCount() {
        if (mList == null || mList.size() <= 1) {
            return 1;
        } else {
            return mList.size();
        }
    }

    @Override
    public boolean isViewFromObject(View arg0, Object arg1) {
        return arg0 == arg1;
    }

    @Override
    public void destroyItem(View container, int position, Object object) {
        ((ViewPager) container).removeView((View) object);
    }

    @Override
    public Object instantiateItem(View container, final int position) {
        final RelativeLayout rl = (RelativeLayout) View.inflate(mContext, R.layout.layout_community_content, null);
        //添加tag设置，刷新时通过tag判断当前view
//        rl.setTag(position);
        final CoverLoading cover = (CoverLoading) rl.findViewById(R.id.cv_community_content);

        final SmartRefreshLayout srl = (SmartRefreshLayout) rl.findViewById(R.id.srl_item_community);

        final FooterListView flv = (FooterListView) rl.findViewById(R.id.flv_item_community);

        final FeedListAdapter fAdapter = new FeedListAdapter(mContext,new ArrayList<RecommendFeed.DataBean.ListBean>(),"");

        flv.setAdapter(fAdapter);

        flv.setOnFooterClickListener(new FooterListView.FooterClickListener() {
            @Override
            public void onFooterClicked() {
                getTopicData(mList.get(position).getId(), rl, fAdapter,LOAD_MORE);
            }
        });
        flv.setOnLastItemVisiableListener(new FooterListView.LastItemVisiableListener() {
            @Override
            public void onLastItemVisiable() {
                getTopicData(mList.get(position).getId(), rl, fAdapter,LOAD_MORE);
            }
        });

        cover.setOnReloadClickListener(new CoverLoading.ReloadListener() {
            @Override
            public void onReloadClicked() {
                getTopicData(mList.get(position).getId(), rl, fAdapter,PULL_REFRESH);
            }
        });
        cover.setResult(CoverLoading.LoadingResult.LOADING);


        srl.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {

            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {

            }
        });

//        getAllData(rl, fAdapter,position);

        ((ViewPager) container).addView(rl);
        return rl;
    }


    public void setList(List<RecommendData.DataBean.CategoryBean> list) {
        if (mList == null) {
            mList = new ArrayList<RecommendData.DataBean.CategoryBean>();
        }
        mList = list;
        notifyDataSetChanged();
    }

    public void addList(List<RecommendData.DataBean.CategoryBean> list) {
        if (mList == null) {
            mList = new ArrayList<RecommendData.DataBean.CategoryBean>();
        }
        mList.addAll(list);
        notifyDataSetChanged();
    }

    public void clearList() {
        if (mList != null) {
            mList.clear();
            notifyDataSetChanged();
        }
    }

    //TODO 可以抽取显示方式之后优化时候来做
    private static final int PULL_REFRESH = 0;
    private static final int LOAD_MORE = 1;
    private void getTopicData(String category_id, final RelativeLayout container,final FeedListAdapter adapter, final int code){

        TreeMap<String,String> map = new TreeMap<>();
        map.put("category_id",category_id);
        map.put("pagesize","10");
        String index = String.valueOf(adapter.getCount()/10+1);
        map.put("page",index);

        HttpClient.post(SERVER + DISCOVER_FEED, map, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //TODO 如果是第一页，则
                //TODO 如果不是第一页则通知footer result
//                Log.e("TAG",e.getMessage().toString());

                ((Activity)mContext).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        switch (code){
                            case PULL_REFRESH:
                                ((CoverLoading)container.findViewById(R.id.cover)).setResult(CoverLoading.LoadingResult.FAIL);
                                break;
                            case LOAD_MORE:
                                ((CoverLoading)container.findViewById(R.id.cover)).setResult(CoverLoading.LoadingResult.SUCCESS);
                                ((FooterListView) container.findViewById(R.id.flv_topic_content)).setResult(FooterListView.ActionResult.ERROR);
                                break;
                        }

                        if(container.findViewById(R.id.srl_topic_content) != null){
                            ((SwipeRefreshLayout) container.findViewById(R.id.srl_topic_content)).setRefreshing(false);
                        }
                    }
                });
            }

            //抽一下，没时间。。。
            @Override
            public void onResponse(final Call call, String response) {
                final RecommendFeed data = new Gson().fromJson(response,RecommendFeed.class);

                ((Activity)mContext).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        switch (code){
                            case PULL_REFRESH:
                                //有数据
                                if(data != null && data.getData() != null && data.getData().getList() != null && data.getData().getList().size()>0){
                                    adapter.setList(data.getData().getList());
                                    ((CoverLoading)container.findViewById(R.id.cover)).setResult(CoverLoading.LoadingResult.SUCCESS);
                                    if(data.getData().getList().size()<=0){
                                        //no more
                                        ((FooterListView) container.findViewById(R.id.flv_topic_content)).setResult(FooterListView.ActionResult.NO_MORE);
                                    }else{
                                        ((FooterListView) container.findViewById(R.id.flv_topic_content)).setResult(FooterListView.ActionResult.HAS_MORE);
                                    }

                                }else{
                                    ((CoverLoading)container.findViewById(R.id.cover)).setResult(CoverLoading.LoadingResult.NULL);
                                    ((FooterListView) container.findViewById(R.id.flv_topic_content)).setResult(FooterListView.ActionResult.NO_MORE);
                                }
                                break;
                            case LOAD_MORE:
                                if(data != null && data.getData() != null && data.getData().getList() != null && data.getData().getList().size()>0){
                                    adapter.addList(data.getData().getList());
                                    ((CoverLoading)container.findViewById(R.id.cover)).setResult(CoverLoading.LoadingResult.SUCCESS);
                                    if(data.getData().getList().size()<=0){
                                        //no more
                                        ((FooterListView) container.findViewById(R.id.flv_topic_content)).setResult(FooterListView.ActionResult.NO_MORE);
                                    }else{
                                        ((FooterListView) container.findViewById(R.id.flv_topic_content)).setResult(FooterListView.ActionResult.HAS_MORE);
                                    }
                                }else{
                                    ((CoverLoading)container.findViewById(R.id.cover)).setResult(CoverLoading.LoadingResult.SUCCESS);
                                    ((FooterListView) container.findViewById(R.id.flv_topic_content)).setResult(FooterListView.ActionResult.NO_MORE);
                                }
                                break;
                        }

                        if((container.findViewById(R.id.srl_topic_content)) != null){
                            ((SwipeRefreshLayout) container.findViewById(R.id.srl_topic_content)).setRefreshing(false);
                        }
                    }
                });
            }
        });
    }

    private void getAllData(final RelativeLayout container, final FeedListAdapter adapter,final int position){

        final CoverLoading cover = (CoverLoading) container.findViewById(R.id.cover);
        final FooterListView flv = (FooterListView) container.findViewById(R.id.flv_topic_content);
        final String category_id = mList.get(position).getId();
        TreeMap<String, String> map = new TreeMap<>();
        map.put("category_id",category_id);
        map.put("pagesize","10");

        HttpClient.post(HttpConfig.SERVER+HttpConfig.DISCOVER, map, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

                ((Activity)mContext).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(cover!=null){
                            cover.setResult(CoverLoading.LoadingResult.FAIL);
                        }
                    }
                });
            }

            @Override
            public void onResponse(Call call, final String response)   {
//                final String s = response.body().string();
//                LogUtils.i("data",s);
                final RecommendData data = new Gson().fromJson(response,RecommendData.class);

                ((Activity)mContext).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//                        Log.e("TAG","response="+s);
                        if(data.getData() == null){
                            if(cover!=null){
                                cover.setResult(CoverLoading.LoadingResult.NULL);
                            }
                            return;
                        }

                        List<RecommendData.DataBean.PlayCoversBean> recommendList = data.getData().getPlay_covers();
                        List<RecommendData.DataBean.AudioListBean> feedList = data.getData().getAudio_list();
                        //跳转播单分类定位
                        flv.setRecommendHeaderData(recommendList,category_id);
                        //TODO TODO 添加banner数据获取接口
                        List<RecommendData.DataBean.BannerBean> banner = data.getData().getBanner();
                        for (int i=0;i<banner.size();i++){
                            if (!"1".equals(banner.get(i).getType()) && !"3".equals(banner.get(i).getType())){
                                banner.remove(i);
                                i--;
                            }
                        }
                        flv.setBannerData(banner);
                        flv.setF4(data.getData().getTool());

                        //-----FIXME cover坑，分清cover，先这样
                        if(feedList != null && feedList.size()>0){
//                            adapter.setList(changeBean(feedList));
                            cover.setResult(CoverLoading.LoadingResult.SUCCESS);
                            if(feedList.size()<=0){
                                //no more
                                flv.setResult(FooterListView.ActionResult.NO_MORE);
                            }else{
                                flv.setResult(FooterListView.ActionResult.HAS_MORE);
                            }
                        }else{
                            cover.setResult(CoverLoading.LoadingResult.NULL);
                            flv.setResult(FooterListView.ActionResult.NO_MORE);
                        }
                        //------

                        if(cover!=null){
                            cover.setResult(CoverLoading.LoadingResult.SUCCESS);
                        }
                    }
                });


            }
        });
    }


}
